package com.manage;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.manage.adapter.AccountedOrderDetailAdapter;
import com.manage.base.BaseActivity;
import com.manage.model.Order;
import com.manage.model.OrderItem;
import com.manage.sharedpreferences.SPConfig;
import com.manage.util.RequestUtils;
import com.manage.util.StringUtil;

/**
 * 账目统计中的订单详情列表
 * @author liyoro
 *
 */
public class AccountsOrderDetailActivity extends BaseActivity implements OnClickListener, OnScrollListener {

	private static String TAG = "AccountsOrderDetailActivity";
	
	private TextView tvSelect = null;
	private PopupWindow selectWindow;
	
	private AccountedOrderDetailAdapter orderAdapter = null;

	// 加载
	private View loadingLayout;
	private ProgressBar progressBar;
	private TextView errText;
	
	//分页
	private int lastItem = 0;
	private boolean isEndFlag = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.accounted_order_detail_list);
		initDatas();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
//		initDatas();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
//		page = 1;
//		initDatas();
	}
	
	@Override
	public String getLeftBtnName() {
		return "返回";
	}

	@Override
	public String getTitleName() {
		return "订单列表";
	}

	@Override
	public boolean showButton() {
		return true;
	}

	@Override
	public void initView() {
		orderListview = (ListView) findViewById(R.id.listview1);

		// 加载更多
		loadingLayout = ((LayoutInflater)AccountsOrderDetailActivity
				  .this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
				  .inflate(R.layout.more_row, null, false);

		// 加载到listActivity的底部
		orderListview.addFooterView(loadingLayout);
		
		orderAdapter = new AccountedOrderDetailAdapter(this);
		orderListview.setAdapter(orderAdapter);
		orderListview.setOnScrollListener(this);
		
		loadingLayout.setOnClickListener(this);
		loadingLayout.setClickable(false);
		
		progressBar = (ProgressBar)loadingLayout.findViewById(R.id.progressbar);
		errText = (TextView)loadingLayout.findViewById(R.id.err_text);
		
		tvSelect = (TextView)findViewById(R.id.popup_item_pending_accept_msg);
		tvSelect.setOnClickListener(this);
	}
	
	public void showProgress() {
		progressBar.setVisibility(View.VISIBLE);
		errText.setText("正在加载数据...");
		
		if(orderListview.getFooterViewsCount() == 0) {
			Log.d(TAG, "listView.getFooterViewsCount() == 0");
			orderListview.addFooterView(loadingLayout);
		}
	}
	
	public void hideProgress() {
		errText.setText("正在加载数据...");
		
		if(orderListview.getFooterViewsCount() != 0) {
			orderListview.removeFooterView(loadingLayout);
		}
	}
	
	public void showAgainProgress() {
		loadingLayout.setClickable(true);
		loadingLayout.setVisibility(View.VISIBLE);
		orderListview.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.GONE);
		errText.setVisibility(View.VISIBLE);
		errText.setText("获取数据失败，点击重试！");
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) { 
			switch(msg.what) {
			case SUCCESS:

				if(orderList.size() < 5) {
					hideProgress();
				}
				
				Bundle bundle = msg.getData();
				String res = bundle.getString("res");

				if(res != null && !res.equals("[{}]") && res.length() > 15) {
					JSONArray jsonTemp = StringUtil.getJson(res);

					try {
						for(int i=0; i<jsonTemp.length(); i++) {
							Order order = new Order();
							JSONObject temp = new JSONObject(jsonTemp.getString(i));
							JSONObject temp0 = new JSONObject(temp.getString("order"));
							
							order.setOrderID(temp0.getString("order_id"));
							order.setOrderTime(temp0.getString("order_time"));
							order.setDeliveryCosts(temp0.getString("delivery_costs"));
							order.setClientAddition(temp0.getString("remark"));
							order.setStatus(temp0.getString("order_stause"));
							
							JSONObject temp2 = new JSONObject(temp.getString("user"));
							order.setClientName(temp2.getString("appellation"));
							order.setPhoneNumber(temp2.getString("tel"));
							order.setClientAddress(temp2.getString("address"));
							order.setRemark(temp2.getString("remark"));

							//菜品
							JSONArray temp3 = new JSONArray(temp0.getString("dishes"));
							ArrayList<OrderItem> dishesList = new ArrayList();
							
							for(int j=0; j< temp3.length(); j++) {
								OrderItem dish = new OrderItem();
								
								JSONObject temp4 = new JSONObject(temp3.getString(j));
								dish.setCaipin_ID(temp4.getString("dishes_id"));
								dish.setCaipin_name(temp4.getString("name"));
								dish.setCaipin_count(temp4.getString("count"));
								dish.setCaipin_price(temp4.getString("price"));
								
								dishesList.add(dish);
							}
							order.setDishes(dishesList);

							//删除的菜品
							JSONArray temp5 = new JSONArray(temp0.getString("del_dishes"));
							ArrayList<OrderItem> deldishesList = new ArrayList();
							
							for(int j=0; j< temp5.length(); j++) {
								OrderItem dish = new OrderItem();
								
								JSONObject temp6 = new JSONObject(temp5.getString(j));
								dish.setCaipin_ID(temp6.getString("dishes_id"));
								dish.setCaipin_name(temp6.getString("name"));
								dish.setCaipin_count(temp6.getString("count"));
								dish.setCaipin_price(temp6.getString("price"));
								
								deldishesList.add(dish);
							}
							order.setDelDishes(deldishesList);
							
							//新增的菜品
							JSONArray temp7 = new JSONArray(temp0.getString("add_new"));
							ArrayList<OrderItem> adddishesList = new ArrayList();
							
							for(int j=0; j< temp7.length(); j++) {
								OrderItem dish = new OrderItem();
								
								JSONObject temp8 = new JSONObject(temp7.getString(j));
								dish.setCaipin_ID(temp8.getString("dishes_id"));
								dish.setCaipin_name(temp8.getString("name"));
								dish.setCaipin_count(temp8.getString("count"));
								dish.setCaipin_price(temp8.getString("price"));
								
								adddishesList.add(dish);
							}
							order.setAddDishes(adddishesList);
							
							orderList.add(order);
						}
						Log.i(TAG, ":" + orderList.size());
						orderAdapter.setValue(orderList);
					}
					catch (JSONException e) {
						e.printStackTrace();
					} 
					catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					isEndFlag = true;
					hideProgress();
					Toast.makeText(AccountsOrderDetailActivity.this, "已经是最后一页", 
							Toast.LENGTH_SHORT).show();
				}
				
				break;
			case FAIL:
//				ToastUtils.show(AccountsOrderDetailActivity.this, "配送订单操作失败，请稍侯重试！", true);
				showAgainProgress();
				break;
			}
		}
	};
	
	@Override
	public void initDatas() {
		showProgress();
		orderList.clear(); 

		if(page == 1) {
			orderList.clear();
			orderAdapter.setValue(null);
			orderAdapter.setClear(true);
		} else {
			orderAdapter.setClear(false);
		}
		
		String shopID = sp.getString(SPConfig.SHOPID, "");
		String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
		String currentSelect = sp.getString(SPConfig.CURRENTORDERTYPE, "1");
		
		if(currentSelect.equals("1")) {
			tvSelect.setText("待受理");
		} 
		else if(currentSelect.equals("2")){
			tvSelect.setText("待配送");
		} 
		else if(currentSelect.equals("3")){
			tvSelect.setText("待入账");
		} 
		else if(currentSelect.equals("4")){
			tvSelect.setText("已完成");
		} 
		else if(currentSelect.equals("5")){
			tvSelect.setText("已取消");
		}
		
		RequestUtils.getOrderData(shopID, token, currentSelect, String.valueOf(page), handler, this.requestList);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.popup_item_pending_accept_msg:
			showSelectPop(tvSelect);
			break;
		case R.id.more_self:
			initDatas();
			break;
		}
	}

	/**
	 * 订单状态选项dialog
	 * 1:待受理订单，2：待配送订单，3：待入账订单，4：已完成,5:已取消
	 * @author liyoro
	 *
	 */
	private void showSelectPop(View parent) {
		View view = null;
		
		TextView item_pending_accept = null;
		TextView item_pending_delivery = null;
		TextView item_pending_accounted = null;
		TextView item_complete = null;
		TextView item_cancel = null;
		
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view = layoutInflater.inflate(R.layout.order_type_popup_filter_msg, null);
		
		// 创建一个PopuWidow对象
		selectWindow = new PopupWindow(view, 200, 500);
		
		// 使其聚集
		selectWindow.setFocusable(true);
		
		// 设置允许在外点击消失
		selectWindow.setOutsideTouchable(true);
		
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		selectWindow.setBackgroundDrawable(new BitmapDrawable());
		
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
		int xPos = ((windowManager.getDefaultDisplay().getWidth()-50)/ 4)
				- selectWindow.getWidth() / 2;
		selectWindow.showAsDropDown(parent, xPos, 0);
		
		item_pending_accept = (TextView)view.findViewById(R.id.popup_item_pending_accept_msg);
        item_pending_delivery = (TextView)view.findViewById(R.id.popup_item_pending_delivery_msg);
        item_pending_accounted = (TextView)view.findViewById(R.id.popup_item_pending_accounted_msg);
        item_complete = (TextView)view.findViewById(R.id.popup_item_complete_msg);
        item_cancel = (TextView)view.findViewById(R.id.popup_item_cancel_msg);
        
        View.OnClickListener _selectListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switch(v.getId()) {
				case R.id.popup_item_pending_accept_msg:
					tvSelect.setText("待受理");
					sp.setString(SPConfig.CURRENTORDERTYPE, "1");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.popup_item_pending_delivery_msg:
					tvSelect.setText("待配送");
					sp.setString(SPConfig.CURRENTORDERTYPE, "2");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.popup_item_pending_accounted_msg:
					tvSelect.setText("待入账");
					sp.setString(SPConfig.CURRENTORDERTYPE, "3");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.popup_item_complete_msg:
					tvSelect.setText("已完成");
					sp.setString(SPConfig.CURRENTORDERTYPE, "4");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.popup_item_cancel_msg:
					tvSelect.setText("已取消");
					sp.setString(SPConfig.CURRENTORDERTYPE, "5");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				}
			}
		};
		
		item_pending_accept.setOnClickListener(_selectListener);
        item_pending_delivery.setOnClickListener(_selectListener);
        item_pending_accounted.setOnClickListener(_selectListener);
        item_complete.setOnClickListener(_selectListener);
        item_cancel.setOnClickListener(_selectListener);
        
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount-1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(true == isEndFlag){
			return;
		}
		showProgress();
		
		if (lastItem == orderAdapter.getCount() 
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			page++;
//			Log.d(TAG, "nowpage:" + page);
			initDatas();
		}
	}
}
